package com.dana.friend.service.user.impl;

import cn.hutool.core.bean.BeanUtil;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.core.constants.Constants;
import com.core.constants.ProgramType;
import com.core.constants.QuestionRestType;
import com.core.domain.Result;
import com.core.enums.ResultCode;
import com.core.utils.ThreadLocalUtils;
import com.dana.api.RemoteJudgeService;
import com.dana.api.domain.UserExeResult;
import com.dana.api.domain.dto.JudgeSubmitDTO;
import com.dana.api.domain.vo.UserQuestionResultVO;
import com.dana.friend.domain.question.Question;
import com.dana.friend.domain.question.QuestionCase;
import com.dana.friend.domain.question.es.QuestionES;
import com.dana.friend.domain.user.UserSubmit;
import com.dana.friend.domain.user.dto.UserQuestionSubmitDTO;
import com.dana.friend.elasticsearch.QuestionRepository;
import com.dana.friend.mapper.user.UserSubmitMapper;
import com.dana.friend.mapper.question.QuestionMapper;
import com.dana.friend.rabbit.JudgeProducer;
import com.dana.friend.service.user.IUserQuestionService;
import com.dana.security.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserQuestionServiceImpl implements IUserQuestionService {
    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private RemoteJudgeService remoteJudgeService;
    @Autowired
    private JudgeProducer judgeProducer;
    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Override
    public Result<UserQuestionResultVO> submit(UserQuestionSubmitDTO userQuestionSubmitDTO) {
        //判断语言类型
        Integer programType = userQuestionSubmitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType)){
            //按照Java逻辑处理
            JudgeSubmitDTO judgeSubmitDTO=assmbleJudgeSubmitDTO(userQuestionSubmitDTO);
            //远程调用doJudgeJavaCode方法
            return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
        }
        throw new ServiceException(ResultCode.NOT_SUPPORT_PROGRAM);
    }

    @Override
    public boolean rabbitmqSubmit(UserQuestionSubmitDTO userQuestionSubmitDTO) {
        //判断语言类型
        Integer programType = userQuestionSubmitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType)) {
            //按照Java逻辑处理
            JudgeSubmitDTO judgeSubmitDTO = assmbleJudgeSubmitDTO(userQuestionSubmitDTO);
            judgeProducer.produceMsg(judgeSubmitDTO);
            return true;
        }
        throw new ServiceException(ResultCode.NOT_SUPPORT_PROGRAM);
    }

    @Override
    public UserQuestionResultVO exeResult(Long examId, Long questionId, String currentTime) {
      Long userId = ThreadLocalUtils.get(Constants.USER_ID,Long.class);
        UserSubmit userSubmit = userSubmitMapper.selectCurrentUserSubmit(userId, examId, questionId, currentTime);
        UserQuestionResultVO userQuestionResultVO=new UserQuestionResultVO();
        if (userSubmit==null){
            userQuestionResultVO.setPass(QuestionRestType.IN_JUDGE.getValue());
        }else {
            userQuestionResultVO.setPass(userSubmit.getPass());
            userQuestionResultVO.setExeMessage(userSubmit.getExeMessage());
            if (StrUtil.isNotEmpty(userSubmit.getCaseJudgeRes())){
                userQuestionResultVO.setUserExeResultList(JSON.parseArray(userSubmit.getCaseJudgeRes(), UserExeResult.class));
            }
        }
        return userQuestionResultVO;
    }

    private JudgeSubmitDTO assmbleJudgeSubmitDTO(UserQuestionSubmitDTO userQuestionSubmitDTO) {
        //先去es中查询题目相关信息
        JudgeSubmitDTO judgeSubmitDTO=new JudgeSubmitDTO();
        QuestionES questionES = questionRepository.findById(userQuestionSubmitDTO.getQuestionId()).orElse(null);
        if (questionES != null){
            //将es中的数据存储到judgeSubmitDTO
            BeanUtil.copyProperties(questionES,judgeSubmitDTO);
        }else {
            //es中不存在直接去数据库中查询
            Question question = questionMapper.selectById(userQuestionSubmitDTO.getQuestionId());
            BeanUtil.copyProperties(question,judgeSubmitDTO);
            questionES=new QuestionES();
            BeanUtil.copyProperties(question,questionES);
            questionRepository.save(questionES);
        }
        //从前端传递的参数中获取信息
        judgeSubmitDTO.setExamId(userQuestionSubmitDTO.getExamId());
        judgeSubmitDTO.setUserId(ThreadLocalUtils.get(Constants.USER_ID,Long.class));
        judgeSubmitDTO.setProgramType(userQuestionSubmitDTO.getProgramType());
        judgeSubmitDTO.setUserCode(codeConnect(userQuestionSubmitDTO.getUserCode(), questionES.getMainFuc()));
        List<QuestionCase> questionCaseList = JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);
        //测试用例输入集合
        List<String> inputList = questionCaseList
                .stream()
                .map(QuestionCase::getInput)
                .toList();
        judgeSubmitDTO.setInputList(inputList);
        //测试用例输出集合
        List<String> outputList = questionCaseList
                .stream()
                .map(QuestionCase::getOutput)
                .toList();
        judgeSubmitDTO.setOutputList(outputList);

        return judgeSubmitDTO;
    }

    /**
     * 拿到用户输入的代码并且拼接main函数
     * @param userCode 用户输入
     * @param mainFunc main函数
     * @return 完整的代码
     */
    private String codeConnect(String userCode, String mainFunc) {
        String targetCharacter = "}";
        int targetLastIndex = userCode.lastIndexOf(targetCharacter);
        if (targetLastIndex != -1) {
            return userCode.substring(0, targetLastIndex) + "\n" + mainFunc + "\n" + userCode.substring(targetLastIndex);
        }
        throw new ServiceException(ResultCode.FAILED);
    }
}
